package com.chen.nio.demo;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.*;

public class NioServer {

    private static Map<String, SocketChannel> map = new HashMap<>();

    public static void main(String[] args) throws Exception {
        /**
         * 1.创建Selector
         */
        Selector selector = Selector.open();
        /**
         * 2.1 创建一个ServerSocketChannel，配置成非阻塞状态，绑定端口号,并且注册到selector上
         * 2.2 然后第二个参数是Selectionkey.OP_ACCEPT，这个是一个interest set，表示的是服务端
         * 关注了可接受客户端连接的事件，当事件触发并且就绪，特定的代码会被触发。
         */
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(8899));
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        /**
         * 3. Nio都是有一个死循环，selector.select方法是阻塞的，返回的值是interest set集合的
         * 数量也就是关注的事件的数量
         * selector.selectionKey()是selector.select返回之前所注册的并且已经发生的事件
         * 的SelectionKey的集合，通过SelectionKey可以获取到已经就绪的事件的集合，以及可以追溯
         * 到与之关联的channel对象
         */
        while (true) {
            int count = selector.select();
            System.out.println("准备好io操作的数量:" + count);
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                /**
                 * 4.遍历selection.selectionKey()，检测channel的什么事件或者操作已经准备就绪
                 *      selectionKey.isAcceptable()
                 *      selectionKey.isConnectable()
                 *      selectionKey.isReadable()
                 *      selectionKey.isWritable()
                 */
                SelectionKey selectionKey = iterator.next();
                if (selectionKey.isAcceptable()) {
                    /**
                     * 5.接受客户端的SokcetChannel连接，并将SokcetChannel设置成非阻塞的
                     * 然后注册到Selector上，并且对读事件感兴趣
                     */
                    ServerSocketChannel ssc = (ServerSocketChannel) selectionKey.channel();
                    SocketChannel socketChannel = ssc.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    map.put(UUID.randomUUID().toString(), socketChannel);
                    System.out.println("获得客户端的连接" + socketChannel);
                } else if (selectionKey.isReadable()) {
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    ByteBuffer sendBuffer = ByteBuffer.allocate(1024);
                    while (true) {
                        buffer.clear();
                        int read = socketChannel.read(buffer);
                        if (read <= 0) {
                            break;
                        }
                        buffer.flip();
                        Charset charset = Charset.forName("utf-8");
                        String message = String.valueOf(charset.decode(buffer).array());
                        System.out.println(socketChannel + ":" + message);
                        Set<String> keySet = map.keySet();
                        String clientId = "";
                        for (String key : keySet) {
                            SocketChannel sc = map.get(key);
                            if (sc == socketChannel) {
                                clientId = key;
                                break;
                            }
                        }
                        String sendMsg = "from client:" + clientId + ",content=" + message;
                        for (String key : keySet) {
                            SocketChannel sc = map.get(key);
                            sendBuffer.clear();
                            sendBuffer.put(sendMsg.getBytes());
                            sendBuffer.flip();
                            sc.write(sendBuffer);
                        }
                    }
                }
                /**
                 * 每一次遍历都要将操作过的selectionKey从selector清除，不然下次还会触发
                 */
                selectionKeys.clear();
                System.out.println("删除selectionKey");
            }
        }
    }

}
